import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Form, Radio, message, TreeSelect, Badge, Popover, Divider, Spin } from 'antd';
import { connect } from 'umi';
import { BaseWrapper } from '@/pages/Organization/OrgFlow/components';
import { getFunctionalList } from '@/services/Organization/orgmanage';
import Difference from '@/pages/WorkFlow/components/FormControls/components/Difference';
import { size } from 'lodash';
import AuthTable from './AuthTable';
import { getAuthData } from '../../service';
import styles from './postForm.less';

// 差异化内容
const ModifyContent = ({ title, addArr, delArr }) => (
    <>
        <div style={{ fontSize: 14, fontWeight: 'bold', marginBottom: 10 }}>{title}：</div>
        {addArr.map(item => (
            <div className={styles.modifyContent}>
                <Badge status="success" style={{ width: '14px' }} />
                <p>新增：{item}</p>
            </div>
        ))}

        {delArr.map(item => (
            <div className={styles.modifyContent}>
                <Badge status="error" style={{ width: '14px' }} />
                <p>删除：{item}</p>
            </div>
        ))}
    </>
);

const PostAuth = ({ wrapperLayout, data: dataSource, modify }) => {
    const tips = dataSource?.tips;
    const oldBusinessData = dataSource?.oldBusinessData;
    const oldDataOrganizationCodes = oldBusinessData?.dataOrganizationCodes;
    const [selectOrgName, setSelectOrgName] = useState([]);
    const [selectOldOrgName, setSelectOldOrgName] = useState([]);
    const [department, setDepartment] = useState(null);
    const [authTree, setAuthTree] = useState(null);
    const [currentTree, setCurrentTree] = useState(null);
    const [visibleModify, setVisibleModify] = useState(false);
    const postAuthPopoverRef = useRef();
    const [departmentLoading, setDepartmentLoading] = useState(false);
    const authType = {
        1: '全集团',
        2: '本公司',
        4: '本部门',
        3: '指定范围'
    };

    const filterTree = tree =>
        tree.map(({ children, ...props }) => {
            if (children && children.length > 0) {
                return { children: filterTree(children), ...props };
            }
            return { children: '', ...props };
        });
    // 部门格式化渲染
    const renderDepartmentTreeNodes = departmentTrees =>
        departmentTrees &&
        departmentTrees.map(item => {
            const title = item.organizationName;
            if (item.children) {
                return (
                    <TreeSelect.TreeNode title={title} key={item.organizationCode} value={item.organizationCode}>
                        {renderDepartmentTreeNodes(item.children)}
                    </TreeSelect.TreeNode>
                );
            }
            return <TreeSelect.TreeNode key={item.organizationCode} title={title} value={item.organizationCode} />;
        });

    // 部门
    const dataDepartment = (
        <Spin spinning={departmentLoading}>
            <TreeSelect
                treeCheckable
                placeholder="请指定部门"
                style={{
                    zIndex: '100',
                    overflow: '-webkit - paged - x',
                    display: 'block'
                }}
                allowClear
                showCheckedStrategy={TreeSelect.SHOW_ALL}
                value={selectOrgName}
                disabled
            >
                {renderDepartmentTreeNodes(department)}
            </TreeSelect>
        </Spin>
    );

    // 数据权限选项
    const radioGroup = (
        <Radio.Group value={dataSource?.dataScope} disabled>
            <Radio value={1}>全集团</Radio>
            {/* <Radio value={2}>本公司</Radio> */}
            <Radio value={4}>本部门</Radio>
            <Radio value={3}>指定范围</Radio>
        </Radio.Group>
    );
    const filterCode = (data = [], values) => {
        const selectArr = [];
        data.forEach(item => {
            if (values.indexOf(item.organizationCode) > -1) {
                selectArr.push(item.organizationName);
            }
        });
        return selectArr;
    };
    // 获取权限树
    const fetchAuthTree = async () => {
        const params = { status: 0 };
        const { code, data, msg } = await getAuthData(params);
        if (code === 10000) {
            setAuthTree(data);
            setCurrentTree(data.webList);
        } else {
            message.error(msg);
        }
    };
    // 获取部门树
    const fetchOrgTree = async () => {
        setDepartmentLoading(true);
        const { code, data, msg } = await getFunctionalList();
        if (code === 10000) {
            setDepartment(data);
            if (data && dataSource?.dataScope === 3) {
                // 获取指定范围部门，转成成code
                const selectArr = filterCode(data, dataSource?.dataOrganizationCodes);
                setSelectOrgName(selectArr);
            }
            if (data && oldBusinessData?.dataScope === 3) {
                // 获取差异化对比指定范围部门，转成成code
                const selectOldArr = filterCode(data, oldDataOrganizationCodes);
                setSelectOldOrgName(selectOldArr);
            }
            setDepartmentLoading(false);
        } else {
            setDepartmentLoading(false);
            message.error(msg);
        }
    };
    // 切换功能权限
    const handleAuthChange = e => {
        const { value } = e.target;
        if (authTree) {
            setCurrentTree(authTree[value]);
        }
    };
    const authModify = useMemo(() => {
        const {
            add_resource: addResource = [],
            delete_resource: deleteResource = [],
            add_app_resource: addAppResource = [],
            add_desktop_resource: addDesktopResource = [],
            add_web_resource: addWebResource = [],
            delete_app_resource: deleteAppResource = [],
            delete_desktop_resource: deleteDesktopResource = [],
            delete_web_resource: deleteWebResource = []
        } = modify;

        if (size(modify) > 0) {
            setVisibleModify(true);
        } else {
            setVisibleModify(false);
        }
        return {
            addResource,
            deleteResource,
            addAppResource,
            addDesktopResource,
            addWebResource,
            deleteAppResource,
            deleteDesktopResource,
            deleteWebResource
        };
    }, [modify]);

    const content = (
        <div className={styles.authModifyWrap}>
            <ModifyContent title="Web端" addArr={authModify?.addWebResource} delArr={authModify?.deleteWebResource} />
            <Divider />
            <ModifyContent
                title="桌面端"
                addArr={authModify?.addDesktopResource}
                delArr={authModify?.deleteDesktopResource}
            />
            <Divider />
            <ModifyContent title="移动端" addArr={authModify?.addAppResource} delArr={authModify?.deleteAppResource} />
        </div>
    );
    useEffect(() => {
        if (dataSource) {
            fetchOrgTree();
            fetchAuthTree();
        }
    }, [dataSource]);
    return (
        <>
            <BaseWrapper title="权限设置" className={styles.formWrap}>
                <Form {...wrapperLayout}>
                    <Form.Item label="数据权限">
                        <Difference
                            tip={
                                tips?.dataScope === 3
                                    ? `${authType[tips?.dataScope]} : ${selectOldOrgName}`
                                    : authType[tips?.dataScope]
                            }
                        >
                            <div>
                                <Form.Item>{radioGroup}</Form.Item>
                            </div>
                        </Difference>

                        <Form.Item>{dataSource?.dataScope === 3 ? dataDepartment : null}</Form.Item>
                    </Form.Item>
                    <Form.Item label="功能权限">
                        <div>
                            <Radio.Group defaultValue="webList" buttonStyle="solid" onChange={handleAuthChange}>
                                <Radio.Button value="webList">Web端</Radio.Button>
                                <Radio.Button value="desktopList">桌面端</Radio.Button>
                                <Radio.Button value="appList">移动端</Radio.Button>
                            </Radio.Group>
                        </div>
                        {visibleModify ? (
                            <div>
                                <span style={{ color: 'green' }}>新增：{authModify.addResource.length} </span>
                                <span style={{ color: 'red', marginLeft: '20px' }}>
                                    删除: {authModify.deleteResource.length}
                                </span>
                                <Popover
                                    content={content}
                                    title="变更内容"
                                    placement="rightBottom"
                                    arrowPointAtCenter
                                    trigger="click"
                                    align={{ targetOffset: ['0%', 0] }}
                                    overlayClassName={styles.postAuthPopover}
                                    getPopupContainer={() => postAuthPopoverRef.current}
                                >
                                    <span
                                        style={{ marginLeft: '20px', color: '#FFA22D', cursor: 'pointer' }}
                                        ref={postAuthPopoverRef}
                                    >
                                        查看功能权限变更记录
                                    </span>
                                </Popover>
                                <AuthTable
                                    data={filterTree(currentTree || [])}
                                    resourceCodes={dataSource?.resourceCodes}
                                    modify
                                />
                            </div>
                        ) : (
                            <AuthTable
                                data={filterTree(currentTree || [])}
                                resourceCodes={dataSource?.resourceCodes}
                                modify
                            />
                        )}
                    </Form.Item>
                </Form>
            </BaseWrapper>
        </>
    );
};

export default connect(({ dictionary }) => ({
    dictionary
}))(PostAuth);
